<?php
/**
 *
 * User: zhan
 * Date: 2017/9/29 9:00
 *
 */

namespace app\business\controller;


use app\api\logic\System;
use Endroid\QrCode\QrCode;
use think\Db;

class Set extends Common{

	/*
	*	构造函数
	*/
	function __construct(){
		parent::__construct();

	}
	/**
	 * 桌子列表
	 */
	public function seat(){
		$db_seat=db("seat");
		$list=$db_seat->where("shop_id=".$this->user['id'])->paginate(10);
		$count=$db_seat->where("shop_id=".$this->user['id'])->count();
		$this->assign('list',$list);
		$this->assign('count',$count);
		return $this->fetch();
	}

	/**
	 * 新增桌子
	 */
	public function seat_edit(){
		if(request()->isPost()){
			$data = array(
					'name'      =>input("name"),
					'status'    => input('status/d'),
					'shop_id'	 =>$this->user['id'],
			);
			Db::startTrans();
			try {
				$res = db("seat")->insertGetId($data);
				if(!$res) throw new \Exception('添加桌子失败');
				$qrcode['qr_code'] = $this->makeQr($res, $data['shop_id']);
				$res = db("seat")->where("id='$res'")->update($qrcode);
				if(!$res) throw new \Exception('生成二维码失败');
				DB::commit();
			} catch (\Exception $e) {
				// 回滚事务
				Db::rollback();
			}
			$this->redirect(url("set/seat"));
		}
		return $this->fetch();
	}
	/**
	 * 生成桌子二维码
	 */
	public function makeQr($table_id,$shop_id){
		vendor("phpqrcode.phpqrcode");
		$url= request()->domain().'/weixin/index/table?table_id='.$table_id.'&id='.$shop_id;
		$errorCorrectionLevel = 'H';//容错级别
		$matrixPointSize = 6;//生成图片大小
		//生成二维码图片
		$this->checkPath(ROOT_PATH.'public\static\code');
		\QRcode::png($url,ROOT_PATH. 'public\static\code\/'.$table_id.'_'.$shop_id.'.png', $errorCorrectionLevel, $matrixPointSize, 2);
		return 'code/'.$table_id.'_'.$shop_id.'.png';
	}
	/**
	 * 检查目录是否可写
	 * @param  string   $path    目录
	 * @return boolean
	 */
	protected function checkPath($path)
	{
		if (is_dir($path)) {
			return true;
		}
		if (mkdir($path, 0755, true)) {
			return true;
		} else {
			return false;
		}
	}
	/*
    删除桌子
 */
	public function seat_del()
	{
		$id = input('id/d');
		$db_seat=db("seat");
		$seat=$db_seat->where("id='$id' and shop_id=".$this->user['id']) ->find();
		if (is_file(ROOT_PATH . 'public/static/'.$seat['qr_code'])) {
			unlink(ROOT_PATH . 'public/static/'.$seat['qr_code']);
		}
		$del =$db_seat->where("id='$id' and shop_id=".$this->user['id']) ->delete();;
		if($del){
			exit(json_encode(1));
		}else{
			exit(json_encode("删除失败"));
		}
	}
	/**
	 * 满减优惠
	*/
	public function discount(){
		if(request()->isPost()){
			$param=input("full/a");
			$reduce=input("reduce/a");
			$data=array();
			if(!empty($param)){
				$option=array();
				foreach($param as $k=>$v){
					$option[$k]['full']=$v;
					$option[$k]['reduce']=$reduce[$k];
				}
				$data['discount']=serialize($option);
			}
			$res=db("shop")->where("id=".$this->user['id'])->update($data);
			if(!$res)  $this->error('操作失败');
			$this->redirect(url("set/discount"));
		}
	$discount=	db("shop")->where("id=".$this->user['id'])->column("discount");
		if($discount[0]){
			$list=unserialize($discount[0]);
		}else{
			$list=array();
		}
		$this->assign("list",$list);
		return $this->fetch();
	}
	/**
	 * 满减优惠模板
	 */
	public function tpl(){
		return $this->fetch();
	}
	/**
	 * 设置
	 */
	public function index(){
		$data=db("shop")->where("id=".$this->user['id'])->find();
		$data['open_time']=unserialize($data['open_time']);
		$data['delivery_time']=unserialize($data['delivery_time']);
		$data['tell']=explode(",",$data['tell']);
		$this->assign("data",$data);
		return $this->fetch();
	}
	/**
	 * 开关店
	 */
	public function open(){
	$result=(new System())->open();
		if(isset($result['message'])){
			echo $result['message'];
		  }else{
			echo 1;
		}
	}
	/**
	 * 设置店铺简介
	 */
	public function des(){
		$result=(new System())->des();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}
	/**
	* 设置店铺缩少起送
	*/
	public function full_distribution(){
		$result=(new System())->full_distribution();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}
	/**
	 * 设置开关预约
	 */
	public function book(){
		$result=(new System())->book();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}
	/**
	 * 设置是否开启配送
	 */
	public function send(){
		$result=(new System())->send();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}
	/**
	 * 设置营业时间
	 */
	public function opentime(){
		$result=(new System())->opentime();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}
	public function OpenTimeTpl(){
	echo	'<div style="margin-left: 100px;line-height: 40px">
          <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
          <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
		开始时间 <input name="starttime[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
                  结束时间 <input name="endtime[]" type="text" style="width: 150px"   class="textbox textbox_295" value=""/>
      </div>';
	}
	public function DeliveryTimeTpl(){
	echo	'<div style="margin-left: 100px;line-height: 40px">
          <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
          <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
		开始时间 <input name="de_starttime[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
                  结束时间 <input name="de_endtime[]" type="text" style="width: 150px"   class="textbox textbox_295" value=""/>
      </div>';
	}
	public function setopentime(){
		if(request()->isPost()){
			$starttime=input("starttime/a");
			$endtime=input("endtime/a");
			$data=array();
			if(!empty($starttime)){
				$option=array();
				foreach($starttime as $k=>$v){
					$option[$k]['starttime']=$v;
					$option[$k]['endtime']=$endtime[$k];
				}
				$data['open_time']=serialize($option);
			}
			$res=db("shop")->where("id=".$this->user['id'])->update($data);
			if($res===false){
				echo 0;
			}else{
				echo 1;
			}
		}
	}
	public function setdeliverytime(){
		if(request()->isPost()){
			$starttime=input("starttime/a");
			$endtime=input("endtime/a");
			$data=array();
			if(!empty($starttime)){
				$option=array();
				foreach($starttime as $k=>$v){
					$option[$k]['starttime']=$v;
					$option[$k]['endtime']=$endtime[$k];
				}
				$data['delivery_time']=serialize($option);
			}
			$res=db("shop")->where("id=".$this->user['id'])->update($data);
			if($res===false){
				echo 0;
			}else{
				echo 1;
			}
		}
	}
	/**
	 * 设置送餐电话
	 */
	public function tell(){
		$result=(new System())->tell();
		if(isset($result['message'])){
			echo $result['message'];
		}else{
			echo 1;
		}
	}

	public function addTell()
	{
	echo	'<div style="margin-left: 100px;line-height: 40px" >
                      <a href="javascript:;" class="fa fa-move" title="拖动调整此显示顺序">移动</a>&nbsp;
                      <a href="javascript:;" onclick="deleteParam1(this)"  style="margin-top:10px;" title="删除">删除</a>
                      <input name="tell[]" type="text" style="width: 150px"  class="textbox textbox_295"  value=""/>
                  </div>';
	}

	/**
	 * 轮播图
	 */
	public function banner(){
		$id = $this->user['id'];
		$banner = db('banner_index');
		$ban = $banner->where(['shop_id'=>$id])->order('sort desc')->select();
		$shop = db('shop')->where(['id'=>$id])->find();

		foreach ($ban as $key => &$value) {
			$category_name = db('category_goods')->where(['shop_id'=>$value['shop_id'],'id'=>$value['cid']])->value('name');
			$value['cateogry_name'] = $category_name;
		}

		$this->assign("list",$ban);
		$this->assign("id",$id);
		$this->assign("shop",$shop);
		return $this->fetch();
	}
	/**
	 * 轮播添加或修改
	 */
	public function banner_edit(){
		$id = input('id');
		$shop_id = $this->user['id'];
		if(request()->isPost()){
			$data['status'] = input('post.status');
			$data['cid'] = input('post.cid');
			$data['position'] = input('post.position');
			$data['position'] = input('post.position');
			$data['title'] = input('post.title');
			$data['sort'] = input('post.displayorder');
			$data['url'] = input('post.url');
			$data['shop_id'] = $this->user['id'];
			$file = request()->file('bnimage');
			if (!empty($file)) {
				$info = $file->move('./static/uploads');
				if ($info) {
					$data['pic'] = $info->getSaveName();
				} else {
					$this->success($file->getError());
				}
			} else {
				$data['pic'] = input('bne');
			}
			if($id){
				$bnr = db('banner_index')->where("id='$id'")->update($data);
			}else{
				$bnr = db('banner_index')->insert($data);
			}//redirect
			$this->redirect(url('Set/banner'));  //url('Set/banner'));
		}
		$banner=db('banner_index')->where("id='$id'")->find();
		$category_goods = db('category_goods')->where(['shop_id'=>$shop_id])->select();
		//$shop_list = db('shop')->field('shopname,id')->select();

		//$this->assign('shop_list',$shop_list);
		$this->assign('category_goods',$category_goods);
		$this->assign("banner",$banner);
		$this->assign("shop_id",$shop_id);
		return $this->fetch();

	}
	/**
	 * 轮播删除
	 */
	public function banner_del(){
		$bnid = input('id');
		$banner = db('banner_index');
		$del = $banner -> where("id='$bnid'") -> delete();
		if($del){
			exit(json_encode(1));
		}else{
			exit(json_encode("删除失败"));
		}
	}
	/*
	* 活动专区
	*/
	public function activity(){
		$shop_id = $this->user['id'];
		$activity=db("activity_index");
		$list = $activity->where(['shop_id'=>$shop_id])->order('sort desc')->select();

		foreach ($list as $key => &$value) {
			$name = db('category_goods')->where(['id'=>$value['cid']])->value('name');
			$value['category_name'] = $name;
		}

		$shopname = db('shop')->where(['id'=>$shop_id])->value('shopname');

		$this->assign('shopname',$shopname);
		$this->assign('id',$shop_id);
		$this->assign('list',$list);
		return $this->fetch();
	}
	/*
	* 活动专区
	*/
	public function activity_edit(){
		$shop_id=$this->user['id'];
		$id = input("id/d");
		$activity=db("activity_index");
		$detail=$activity->where("id='$id'")->find();
		if(request()->isPost()){
			$file = request()->file('image');
			if($file){
				$info = $file->move('./static/uploads');
				if($info){
					$data['image']= $info->getSaveName();
				}
			}
			$data['title']= input('title');
			$data['cid'] = input('cid');
			$data['sort'] = input('sort');
			$data['shop_id'] = $shop_id;

			if(!empty($id)){
				$activity->where(['id'=>$id])->update($data);
			}else{
				$activity->insert($data);
			}

			$this->redirect(url('Set/activity'));
		}

		$category_goods = db('category_goods')->where(['shop_id'=>$shop_id])->select();

		$this->assign("data",$detail);
		$this->assign("shop_id",$shop_id);
		$this->assign("category_goods",$category_goods);
		return $this->fetch();
	}
	/**
	 * 轮播删除
	 */
	public function activity_del(){
		$bnid = input('id');
		$activity = db('activity_index');
		$del = $activity -> where("id='$bnid'") -> delete();
		if($del){
			exit(json_encode(1));
		}else{
			exit(json_encode("删除失败"));
		}
	}

	/*
	 * 司机列表
	 */
	public function driver()
	{
		$where['shop_id']=$this->user['id'];
		$status=input("status");
		if($status!=''){
			$where['status']=$status;
		}else{
			$where['status']=array('gt',-1);
		}
		if(input("keyword")){
			$where['nickname|mobile']=array("like",'%'.input('keyword').'%');
		}
		if(input("export")){
			$this->export($where);exit;
		}
		$where['isbind'] = 1;
		$list = db("driver_shop")->where($where)->order("id desc")->paginate(10)->each(function($item,$key){
			$item['driver'] = db('driver')->alias('d')
					->join('driver_bankcard dc','d.id=dc.driver_id','LEFT')
					->where(['d.id'=>$item['driver_id']])
					->field('d.sex,d.province,d.city,county,d.street,d.address,d.nickname,d.headimage,d.mobile,d.idcard_number,d.cart_number,d.driving_number,dc.card_num,dc.bank')->find();
			return $item;
		});
//halt($list);
		$this->assign('list',$list);
		$this->assign('count',$list->total());
		$this->assign('status',input("status"));
		$this->assign('type',input("type"));
		$this->assign('keyword',input("keyword"));
		return $this->fetch();
	}

	//司机详情
	public function driverinfo()
	{
		$id = input('id/d');
		$where['shop_id'] = $this->user['id'];
		$where['driver_id'] = $id;
		$sel = db("driver_shop")->where($where)->find();
		if(empty($sel))$this->error('数据不存在');
		$sell = db("route")->where($where)->find();
		if($sell){
			$address = db('route_address')->where('route_sn = '."'".$sell['route_sn']."'")->order('num')->column('address');
			$item['address'] = implode('-',$address);
			$data['line']=$address;
		}
		$data = db('driver')->where(['id'=>$id])->find();
		$this->assign('data',$data);
		return $this->fetch();
	}

	//审核司机申请
	public function drivercheck(){
		$id = input('id/d');
		$status=input("status/d");
		if(!in_array($status,array(0,1,-1))){
			exit(json_encode('参数有误'));
		}
		$db=db("driver_shop");
		$data['status']=$status;
		$data['updatetime']=TIMESTAMP;
		$driver_id=$db->where("id='$id'")->value('driver_id');
		$driver = db('driver')->where(['id'=>$driver_id])->find();
		if($status==1) {
			if ($driver['status'] == 0 || $driver['status'] == -1) {
				exit(json_encode('请先审核司机的状态'));
			}
		}
		$res=$db->where("id='$id'")->update($data);
//		var_dump($res);die;
		if($res){
			exit(json_encode(1));
		}else{
			exit(json_encode(0));
		}
	}

	//解约司机申请
	public function undriver(){
		$id = input('id/d');

		$condition['shop_id'] = $this->user['id'];
		$condition['id'] = $id;

		$res = db('driver_shop')->where($condition)->find();
		if(!$res)return ['message'=>'数据不存在！'];
		if($res['status'] != 1)exit(json_encode('你无权解绑该司机'));//只有审核通过才能解绑
		if($res['isbind']!=1)exit(json_encode('你已经解绑该司机'));
		$data = [
				'isbind'=>-2,
				'updatetime'=>TIMESTAMP
		];

		$res=db('driver_shop')->where("id='$id'")->update($data);
//		var_dump($res);die;
		if($res){
			exit(json_encode(1));
		}else{
			exit(json_encode(0));
		}
	}
	/*
	* 线路 列表
	*/
	public function route()
	{
		$uid = $this->user['id'];

//		$route = db('route')->where()->field('')->find();
		$where['shop_id']=$this->user['id'];
		$data = db('route')->where($where)->order('id desc')->field('id,route_sn')->paginate(15)->each(function($item,$key){
			$address = db('route_address')->where('route_sn = '."'".$item['route_sn']."'")->order('num')->column('address');
			$item['address'] = implode('-',$address);
			return $item;
		});
//		halt($data);
		$this->assign('route', $data);
		$this->assign('page', $data->render());
		return $this->fetch();
	}

	//线路编辑页
	public function routeedit()
	{
		$id = input('id');
		if($id){
			$this->assign('id', input('id'));
			$route_address = db('route_address')->where(['route_id'=>$id])->select();
//			var_dump($route_address);
			$this->assign('route_address', $route_address);
		}
		return $this->fetch();
	}

	//线路编辑
	public function do_routeedit()
	{
		$id = input('id');
//		var_dump($id);
		$shop_id = $this->user['id'];
		if(request()->isAjax()){
			$specs = input('specs');
			$specs = json_decode($specs,1);
//			var_dump($specs);
			if(!empty($id)){
				$route_sn = db('route')->where(['id'=>$id,'shop_id'=>$shop_id])->value('route_sn');
			}else{
				$route_sn = $this->becomerouteNo();
				$route['route_sn'] = $route_sn;
				$route['shop_id'] = $shop_id;

				$result = db('route')->insert($route);
				$id = db('route')->getLastInsID();
			}

			$data = [];
			foreach($specs as $key=>&$value){
				$data[$key]['lat'] = $value['lat'];
				$data[$key]['num'] = $key+1;
				$data[$key]['lng'] = $value['lng'];
				$data[$key]['address'] = $value['address'];
				$data[$key]['route_sn'] = $route_sn;
				$data[$key]['route_id'] = $id;
			}
//var_dump($data);
//			die;
			if(!empty($id)){
				//修改
				$route_a = db('route_address')->where(['route_id'=>$id])->find();
				if(empty($route_a)){
					$result = 1;
				}else{
					$result = db('route_address')->where(['route_id'=>$id])->delete();
				}
				if($result){
					$res = db('route_address')->insertAll($data);
				}

			}else{
				//添加
				if($result){$res = db('route_address')->insertAll($data);};

			}
			if(isset($res)&&$result)exit(json_encode(1));
			exit(json_encode(0));
		}
	}

	//线路详情
	public function routedetail()
	{
		$id = input('id');
		$route = db('route')->where(['id'=>$id])->value('route_sn');
		$data['route_sn'] = $route;
		$address = db('route_address')->where(['route_id'=>$id])->column('address');
		$data['address'] = implode('-',$address);
		$this->assign('data', $data);
		return $this->fetch();
	}

	//设置线路时间
	public function routetimeedit()
	{
		$id = input('id/d');
		if(request()->isAjax())
		{
			$data=[];
			$id = input('id/d');
			$everyday = input('everyday');//每隔几天
			if($everyday !== false){
				$data['every_day'] = $everyday;
			}else{
				$data['every_day'] = 0;
			}

			$days = input('day');//几号
			if($everyday && $days)$this->error('每隔几天送与几号送只能选填选一个');
			if(empty($days)){
				$data['days'] = '';
			}else{
				$data['days'] = $days;
			}

			$specs = input('specs');
			$specs = json_decode($specs,1);
			$everytime = [];
			foreach($specs as $key=>&$val)
			{
				$everytime[] = sprintf("%'.02d", $val['hour']).':'.sprintf("%'.02d", $val['min']).':'.'00';
			}
			if(!empty($everytime)){
				$data['every_time'] = serialize($everytime);
			}else{
				$data['every_time'] = '';
			}

			$res = db('route')->where(['id'=>$id])->update($data);
			if($res)$this->success('编辑成功');
			$this->error('编辑失败');
		}
		$sel = db('route')->where(['id'=>$id])->find();
		if(!empty($sel['days'])){$sel['days']=explode(',', $sel['days']);}
		if(!empty($sel['every_time'])){
			$time = unserialize($sel['every_time']);
			$timearr = [];
			foreach($time as $k=>&$v)
			{
				$timearr[] = explode(':', $v);
			}
			$sel['every_time']=$timearr;
		}
//		halt($sel);
		$this->assign('data', $sel);
		return $this->fetch();
	}

	//线路删除
	public function route_del()
	{
		$id = input('id');
		$shop_id = $this->user['id'];
//		die($sn);
		$where['id'] = $id;
		$where['shop_id'] = $shop_id;
		Db::startTrans();
		try {

			$res = db('route')->where($where)->delete();

			$del = db('route_address')->where(['route_id'=>$id])->delete();
			if(!$del||!$res)throw new \Exception('删除失败');
			Db::commit();
		}catch (\Exception $e) {
			Db::rollback();
			return (json_encode(0));
		}
		return (json_encode(1));
	}

	//绑定司机
	public function routedriver()
	{
		$id = input('id/d');//线路id；
		if(request()->isAjax()){
			$id = input('id/d');
//			die($id);
			$driver_id = input('driver_id/d');
			$data['driver_id'] = $driver_id;
			$res = db('route')->where(['id'=>$id])->update($data);
//			$sql = db('route')->getLastSql();
			if($res)$this->success('绑定成功');
			$this->error('绑定失败');
		}

		$where['shop_id']=$this->user['id'];
		$where['status'] = 1;
		$where['isbind'] = 1;
		$list = db("driver_shop")->where($where)->order("id desc")->paginate(10)->each(function($item,$key){
			$item['driver'] = db('driver')->alias('d')
					->where(['d.id'=>$item['driver_id']])
					->field('d.sex,d.address,d.nickname,d.headimage,d.mobile')->find();
			return $item;
		});
//		halt($list);
		$data = db('route')->where(['id'=>$id])->find();
//		var_dump($data);
		$this->assign('data',$data);
		$this->assign('id',$id);
		$this->assign('driver', $list);
		return $this->fetch();
	}

	public static function becomerouteNo()
	{
		$yearCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
		$routeSn =
				$yearCode[intval(date('Y')) - 2017] . time();
		return $routeSn;
	}
	public function optiontpl()
	{
		return $this->fetch();
	}



}